package com.himore.api.web.controller.modules;

import java.util.*;

import com.himore.api.common.annotation.Log;
import com.himore.api.common.core.controller.BaseController;
import com.himore.api.common.core.domain.AjaxResult;
import com.himore.api.common.core.domain.entity.SysUser;
import com.himore.api.common.core.page.TableDataInfo;
import com.himore.api.common.enums.BusinessType;
import com.himore.api.common.utils.*;
import com.himore.api.common.utils.poi.ExcelUtil;
import com.himore.api.system.service.ISysUserService;
import com.himore.api.web.enums.TaskIdEnum;
import com.himore.api.web.model.*;
import com.himore.api.web.service.ITPictureService;
import com.himore.api.web.service.ITSysTaskService;
import com.himore.api.web.service.ITTaskCompleteInfoService;
import io.swagger.annotations.Api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.himore.api.common.core.domain.AjaxResult.error;
import static com.himore.api.common.core.domain.AjaxResult.success;


/**
 * 图片信息Controller
 * 
 * @author ruoyi
 * @date 2021-01-16
 */
@Api(value = "图片管理")
@RestController
@RequestMapping("/system/picture")
public class TPictureController extends BaseController
{
    @Autowired
    private ITPictureService tPictureService;
    @Autowired
    private ITTaskCompleteInfoService tTaskCompleteInfoService;
    @Autowired
    private ITSysTaskService tSysTaskService;

    @Autowired
    private ISysUserService userService;



    /**
     * 查询图片信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TPicture tPicture)
    {
        startPage();
        List<TPicture> list = tPictureService.selectTPictureList(tPicture);
        return getDataTable(list);
    }

    /**
     * 导出图片信息列表
     */
    @Log(title = "图片信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPicture tPicture)
    {
        List<TPicture> list = tPictureService.selectTPictureList(tPicture);
        ExcelUtil<TPicture> util = new ExcelUtil<TPicture>(TPicture.class);
        return util.exportExcel(list, "picture");
    }

    /**
     * 获取图片信息详细信息
     */
    @GetMapping(value = "/{picId}")
    public AjaxResult getInfo(@PathVariable("picId") Long picId)
    {
        return AjaxResult.success(tPictureService.selectTPictureById(picId));
    }

    /**
     * 新增图片信息
     */
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody TPicture tPicture)
    {

        return toAjax(tPictureService.insertTPicture(tPicture));
    }


    /**
     * 新增图片信息
     */
    @PostMapping(value = "/addBatch")
    public AjaxResult addBatch(@RequestBody TPicture tPicture) {
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            //判断一周内的第一次上传图片是否已经完成
            TTaskCompleteInfo tTaskCompleteInfo = new TTaskCompleteInfo();
            Map<String, Date> params = CommonUtils.getWeekDate();
            Date signBeginDate = params.get("mondayDate");
            Date signEndDate = params.get("sundayDate");
            signEndDate = DateUtils.addTimeTodate(signEndDate,1);
            tTaskCompleteInfo.setSigndateBegin(DateUtils.getYYYYMMDDDate(signBeginDate));
            tTaskCompleteInfo.setSigndateEnd(DateUtils.getYYYYMMDDDate(signEndDate));
            tTaskCompleteInfo.setTaskId(TaskIdEnum.TASK_4.getValue());
            TSysTask sysTask = tSysTaskService.selectTSysTaskById(TaskIdEnum.TASK_4.getValue());
            tTaskCompleteInfo.setUserId(sysUser.getUserId());
            if(!tTaskCompleteInfoService.checkIfTaskComplete(tTaskCompleteInfo)){
                TTaskCompleteInfo completeInfo = new TTaskCompleteInfo();
                completeInfo.setUserId(sysUser.getUserId());
                completeInfo.setTaskId(TaskIdEnum.TASK_4.getValue());
                completeInfo.setCreateTime(DateUtils.getNowDate());
                tTaskCompleteInfoService.insertTTaskCompleteInfo(completeInfo);
                //完成任务加上 对应的积分
                SysUser user = new SysUser();
                user.setUserId(sysUser.getUserId());
                user.setScore(sysTask.getAmount());
                userService.updateScoreOrDrawInfo(user);
            }
            if(null  != tPicture && null!= tPicture.getPicPaths()){
                List<HashMap<String,String>>  picList=tPicture.getPicPaths();
                if(null!= picList && picList.size()>0){
                    for(HashMap<String,String> pic :picList){
                        TPicture temp = new TPicture();
                        temp.setUserId(sysUser.getUserId());
                        temp.setPicPath(pic.get("picPath"));
                        temp.setPicRealPath(pic.get("realPath"));
                        temp.setAccountTime(tPicture.getAccountTime());
                        temp.setCreateTime(DateUtils.getNowDate());
                        tPictureService.insertTPicture(temp);
                    }
                }
            }
            return  AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return error(ErrorCodeUtil.E_500,"批量插入图片异常，请联系管理员！");
        }

    }


    /**
     * 修改图片信息
     */
    @Log(title = "图片信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPicture tPicture)
    {
        return toAjax(tPictureService.updateTPicture(tPicture));
    }

    /**
     * 删除图片信息
     */
	@PostMapping("/delete")
    public AjaxResult remove(@RequestBody TPicture tPicture) {
        try {
            String[] ids = tPicture.getPicPathIds().split(",");
            return toAjax(tPictureService.deleteTPictureByIds(ids));
        }catch (Exception e){
            e.printStackTrace();
            return error(ErrorCodeUtil.E_500,"批量删除图片异常，请联系管理员！");
        }
    }

    /**
     * 根据月
     */
    @Log(title = "查询每天的图片详情", businessType = BusinessType.UPDATE)
    @GetMapping("/getDayInfoByTime")
    public AjaxResult getDayInfoByTime(@RequestParam String  queryTime) {
        try {
            if(StringUtils.isBlank(queryTime)){
                return error("日期不能为空，请重新输入！");
            }
            startPage();
            SysUser user =  SecurityUtils.getLoginUser().getUser();
            String[] params = queryTime.split("-");
            int  year =Integer.parseInt(params[0]);
            int month = Integer.parseInt(params[1]);
            Map param = new HashMap();
            if(StringUtils.isNotEmpty(year+"")){
                param.put("year",year);
            }
            if(StringUtils.isNotEmpty(month+"")){
                param.put("month",month);
            }
            param.put("userId",user.getUserId());
            //List<PicInfoResultVO> list = tPictureService.getDayInfoByTime(param);
            param.put("accountTime",queryTime);
            List<PicDetailInfoVO> dayDetailVOList = tPictureService.selectTDayInfoList(param);
/*            for(PicInfoResultVO vo :list){
                List<PicDetailInfoVO> detailList = new ArrayList<>();
                for(PicDetailInfoVO dayDetailVO: dayDetailVOList){
                    if(dayDetailVO.getDay() .equals(vo.getDateValue())){
                        detailList.add(dayDetailVO);
                    }
                }
                vo.setTPictures(detailList);
            }
          */
            Map  result = new HashMap();
            result.put("picList",dayDetailVOList);

            return success(result);
        }catch (Exception e){
            e.printStackTrace();
            return error("查询每天的账单数据异常，请联系管理员！");
        }
    }




}
